﻿using System.Web.Security;

using Castle.MonoRail.Framework;


using Castle.MonoRail.Framework.Filters;
using StateTheaterDataModel;
using System.Linq;
using System.Data.Linq;
using System.Drawing.Imaging;
using System.Web;
using System;
using System.IO;

namespace StateTheater.Controllers
{
	[DefaultAction]
	public abstract class PlainTextController : SmartDispatcherController
	{
		public void DefaultAction()
		{
			string template = "notfound";

			if (HasTemplate(this.ControllerContext.Name +"/" + Action))
			{
				template = Action;
			}
			
			RenderView(template);
		}
	}

	[Layout("default", "Perry"), Rescue("generalerror")]
	[Filter(ExecuteWhen.BeforeAction, typeof(MobileFilter))]
	public class PerryController : PlainTextController
	{
		public override void Initialize()
		{
			base.Initialize();

			string perryWebFolder = Context.ApplicationPath + "/Views/Perry";
			string perryPCFolder = HttpContext.Server.MapPath(perryWebFolder);

			var years = (from pathName in Directory.GetFiles(perryPCFolder, "perry*.vm")
						 orderby pathName descending
						 select Path.GetFileNameWithoutExtension(pathName).Substring(5)).ToList();

			PropertyBag["years"] = years;

		}
	}

	[Layout("default"), Rescue("generalerror")]
	[Filter(ExecuteWhen.BeforeAction, typeof(MobileFilter))]
	public class SiteController : PlainTextController 
	{
		const string strUniqueID = "Snitz00User";

		public StateTheaterDataContext db { get; set; }

		private void SetAutoLoginCookie(string username, string password, bool hash)
		{
			var cookie = new HttpCookie(strUniqueID);
			cookie.Values["Name"] = username;
			cookie.Values["PWord"] = hash ? Util.ToPWHashString(password) : password;
			cookie.Expires = new DateTime(2030, 12, 31);
			Response.CreateCookie(cookie);
		}


		private void IssueAuthTicket(string username, bool rememberMe)
		{
			var ticket = new FormsAuthenticationTicket(1, username,
													 DateTime.Now,
													 rememberMe ? DateTime.Now.AddMonths(1) : DateTime.Now.AddMinutes(20),
													 rememberMe, username);

			string ticketString = FormsAuthentication.Encrypt(ticket);
			HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketString);
			if (rememberMe)
				cookie.Expires = DateTime.Now.AddYears(1);

			HttpContext.Response.Cookies.Add(cookie);
		}
		public void Login(string username, string password, bool remember)
		{
			if (Membership.Provider.ValidateUser(username, password))
			{
				IssueAuthTicket(username, remember);
				if (remember)
				{
					SetAutoLoginCookie(username, password, true);
				}
			}
			else
			{
				Flash["loginerror"] = "Login Failed";
			}
			CancelView();
			Response.Redirect("Show", "Playing");
		}

		public void FakeLogin(string username)
		{
			if (this.Request.IsLocal || Context.CurrentUser.IsInRole("Admin"))
			{
				username=username.Replace('*', ' ');
				IssueAuthTicket(username, true);
//				FormsAuthentication.RedirectToLoginPage();

				var passwordhash = db.FORUM_MEMBERs.Where(fm => fm.M_NAME == username).Select(fm => fm.M_PASSWORD).First();
				SetAutoLoginCookie(username, passwordhash, false);
			}
			CancelView();
			Response.Redirect("Show", "Playing");
		}

		
		
		public void Logout()
		{
			FormsAuthentication.SignOut();
			Response.RemoveCookie(strUniqueID + "/Name");
			Response.RemoveCookie(strUniqueID + "/PWord");

			SetAutoLoginCookie(null, null, false);
//			FormsAuthentication.RedirectToLoginPage();

			Response.Redirect("Show", "Playing");
			CancelView();
		}

		//public static void ReAuthorize(string username)
		//{
		//    IssueAuthTicket(username, false);
		//}

		//public static void ReAuthorize(int userid)
		//{
		//    StateTheaterDataContext db = new StateTheaterDataContext(Util.ConnectionString);
		//    string username = db.FORUM_MEMBERs.Where(fm=>fm.MEMBER_ID == userid).Select(fm=>fm.M_NAME).FirstOrDefault();
		//    if (!string.IsNullOrEmpty(username))
		//        ReAuthorize(username);
		//}

		public void ImageText([DecodeBinder] string t)
		{
			string fontsize = Request.Params["size"] ?? "small";
			Response.ContentType = "image/gif";
			Util.TextOnImage(t, Response.OutputStream, ImageFormat.Gif, fontsize);
			CancelView(); 
		}

		public void MenuTest()
		{
			Castle.MonoRail.Helpers.GravatarHelper grav = new Castle.MonoRail.Helpers.GravatarHelper();
			PropertyBag["grav"] = grav;
		}

	}
}
